﻿using System;
using RestSharp;
using Web.Base.EventArgs;
using Newtonsoft.Json.Linq;
using System.Web.WebPages;
using Web.Base.Models.Game;
using Ayatta.Common.Extensions;
using Ayatta.Contract.Component;
using System.Collections.Specialized;

namespace Web.Base.GameProxys
{
    /// <summary>
    /// 大侠传
    /// </summary>
    internal sealed class DxzGameClient : GameClient
    {
        private const string Game = "8";
        private const string Opid = "358";

        public DxzGameClient(int gameId): base(gameId)
        {
            DefaultKey = "ctNffm_xvMzRG24I";
            Client.BaseUrl = BaseUrl = "http://up.uuzu.com/api/commonAPI";
        }

        /// <summary>
        /// 获取登录url
        /// </summary>
        /// <param name="guid">用户GUID</param>
        /// <param name="param">参数</param>
        /// <returns></returns>
        public override string GetLoginUri(string guid, params string[] param)
        {
            var sid = param[0] ?? string.Empty;
            var auth = GetAuth(guid, sid);
            var verify = (auth + DefaultKey).ToMd5().ToLower();

            var request = new RestRequest("login");
            request.AddParameter("auth", auth);
            request.AddParameter("verify", verify);
            return Client.BuildUri(request).ToString();
        }

        /// <summary>
        /// 检查用户是否创建角色
        /// </summary>
        /// <param name="guid">用户GUID</param>
        /// <param name="param">参数</param>
        /// <returns></returns>
        public override SkResult<string> CheckUser(string guid, params string[] param)
        {
            var result = new SkResult<string>();

            var sid = param[0] ?? string.Empty;
            var request = new RestRequest("roleverify");

            var auth = GetAuth(guid, sid);
            var verify = (auth + DefaultKey).ToMd5().ToLower();

            request.Timeout = Timeout;
            request.AddParameter("auth", auth);
            request.AddParameter("verify", verify);
            try
            {
                var content = Client.Execute(request).Content;
                var json = JObject.Parse(content);
                var status = json.Value<int>("status") == 0;
                if (status)
                {
                    result.Status = true;
                }
                else
                {
                    result.Message = content;
                }
            }
            catch (Exception e)
            {
                result.Message = e.Message;
            }
            return result;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="guid">用户GUID</param>
        /// <param name="serverId">游戏区服Id</param>
        /// <param name="param">参数</param>
        /// <returns></returns>
        public override SkResult<UserInfo> GetUser(string guid, int serverId, params string[] param)
        {
            var result = new SkResult<UserInfo>();
            var user = new UserInfo(guid) {GameId = GameId, ServerId = serverId};

            var sid = param[0] ?? string.Empty; // 1服为358080001 2服为358080002
            var account = guid;
            var request = new RestRequest("userInfo");
            var auth = GetUserAuth(account, sid);
            var verify = (auth + DefaultKey).ToMd5().ToLower();

            request.Timeout = Timeout;
            request.AddParameter("auth", auth);
            request.AddParameter("verify", verify);

            try
            {
                var url = Client.BuildUri(request).ToString();
                var content = Client.Execute(request).Content;
                if (!string.IsNullOrEmpty(content))
                {
                    var json = JObject.Parse(content.Replace("[]", "null"));
                    var status = json["status"].Value<int>();
                    if (status == 0)
                    {
                        var data = json["data"];
                        if (data[account].HasValues)
                        {
                            var name = data[account]["name"].Value<string>();
                            var level = data[account]["level"].Value<string>();
                            user.RoleName = name;
                            user.Level = level.AsInt();
                            user.ModifiedOn = DateTime.Now;
                            OnUpdated(new EventArgs<UserInfo>(user));
                            result.Data = user;
                        }
                        else
                        {
                            user.RoleName = string.Empty;
                            user.Level = 0;
                        }
                    }
                    else
                    {
                        result.Extra = url;
                        result.Message = content;
                    }
                }
            }
            catch (Exception e)
            {
                result.Message = e.Message;
            }
            return result;
        }

        /// <summary>
        /// 充值
        /// </summary>
        /// <param name="guid">用户GUID</param>
        /// <param name="order">订单</param>
        /// <param name="param">参数</param>
        /// <returns></returns>
        public override SkResult<OrderInfo> Recharge(string guid, OrderInfo order, params string[] param)
        {
            var result = new SkResult<OrderInfo>();

            var sid = param[0] ?? string.Empty;
            var request = new RestRequest("charge");

            var auth = GetRechargeAuth(guid, order, sid);
            var verify = (auth + DefaultKey).ToMd5().ToLower();

            request.Timeout = Timeout;
            request.AddParameter("auth", auth);
            request.AddParameter("verify", verify);
            try
            {
                var content = Client.Execute(request).Content;
                var json = JObject.Parse(content);
                var status = json.Value<int>("status");
                if (status == 0)
                {
                    result.Status = true;
                    OnRecharged(new EventArgs<OrderInfo>(order));
                }
                else
                {
                    result.Message = content;
                }
            }
            catch (Exception e)
            {
                result.Message = e.Message;
            }
            return result;
        }

        private static string GetAuth(string account, string sid)
        {
            var param = new NameValueCollection();
            var time = GetUnixTime();
            param.Add("op_id", Opid);
            param.Add("sid", sid);
            param.Add("game_id", Game);
            param.Add("account", account);
            param.Add("time", time);
            return param.ToQueryString().ToBase64String();
        }

        private static string GetUserAuth(string accounts, string sid)
        {
            var param = new NameValueCollection();
            var time = GetUnixTime();
            param.Add("op_id", Opid);
            param.Add("sid", sid);
            param.Add("game_id", Game);
            param.Add("accounts", accounts);
            param.Add("time", time);
            return param.ToQueryString().ToBase64String();
        }

        private static string GetRechargeAuth(string guid, OrderInfo order, string sid)
        {
            var um = order.Amount;
            var gm = (order.Amount) * 10;
            var param = new NameValueCollection();
            var time = GetUnixTime();
            param.Add("op_id", Opid);
            param.Add("sid", sid);
            param.Add("game_id", Game);
            param.Add("account", guid);
            param.Add("order_id", order.Id);
            param.Add("game_money", gm.ToString("F0"));
            param.Add("u_money", um.ToString("F0"));
            param.Add("time", time);
            return param.ToQueryString().ToBase64String();
        }
    }
}